#include <iostream>

using namespace std;

int a[4], b[4];

int main()
{
    int t; cin >> t;
    while(t--)
    {
          int n; cin >> n;
    for(int i = 1; i <= 3; i++) cin >> a[i] >> b[i];
    int minc = 0x3f3f3f3f;
    int tmp = n;
    if(a[1] <= n)
    {
        tmp -= b[1];
        if(a[2] <= tmp) 
        {
            tmp -= b[2];
            if(tmp >= a[3])
            {
                tmp -= b[3];
            }
        }
    }
    minc = min(minc, tmp);
    tmp = n;
    if(a[1] <= n)
    {
        tmp -= b[1];
        if(a[3] <= tmp) 
        {
            tmp -= b[3];
            if(tmp >= a[2])
            {
                tmp -= b[2];
            }
        }
    }
    minc = min(minc, tmp);
    tmp = n;
    if(a[2] <= n)
    {
        tmp -= b[2];
        if(a[1] <= tmp) 
        {
            tmp -= b[1];
            if(tmp >= a[3])
            {
                tmp -= b[3];
            }
        }
    }
     minc = min(minc, tmp);
     tmp = n;
    if(a[2] <= n)
    {
        tmp -= b[2];
        if(a[3] <= tmp) 
        {
            tmp -= b[3];
            if(tmp >= a[1])
            {
                tmp -= b[1];
            }
        }
    }
     minc = min(minc, tmp);
     tmp = n;
    if(a[3] <= n)
    {
        tmp -= b[3];
        if(a[2] <= tmp) 
        {
            tmp -= b[2];
            if(tmp >= a[1])
            {
                tmp -= b[1];
            }
        }
    }
     minc = min(minc, tmp);
    tmp = n;
    if(a[3] <= n)
    {
        tmp -= b[3];
        if(a[1] <= tmp) 
        {
            tmp -= b[1];
            if(tmp >= a[2])
            {
                tmp -= b[2];
            }
        }
    }
     minc = min(minc, tmp);
    tmp = n;
    cout << max(minc, 0) << endl;
    }
  
    return 0;
}